//
//  RequestTokenObject.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-18.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "RequestTokenOperation.h"
#import "URLFactory.h"
#import "JSON.h"
#import "LFAccount.h"
#import "CoreDataManager.h"
//
@implementation RequestTokenOperation

@synthesize delegate            =           _delegate;

@synthesize successSel          =           _successSel;
@synthesize failSel             =           _failSel;

- (void)dealloc
{
    [super dealloc];
}

- (id)initWithDelegat:(id)delegate_ successSel:(SEL)successSel_ failSel:(SEL)failSel_
{
    self = [super init];
    if (self) 
    {
        self.delegate = delegate_;
        self.successSel = successSel_;
        self.failSel = failSel_;
    }
    
    return self;
}

- (void)main
{
    /*  返回值实例
     {
     api = "com.taobao.client.mtop.getUserSessionKey";
     data =     {
     ecode = AKIGl;
     nick = wdch999;
     sid = 40fb7f89a238315a369c4743bec4f7f4;
     time = 20111118;
     token = 63bdc096c76eec237031d6aacd150c1df24d1b9a34b3a405c355d61399b265c879cd14808fe2e13565785d8e70b8b851db2572a6e867dc8d163d8e44b084960b4bf7901efd8a83d7f2fe01ef8671947f92df1ff519cc39e17553a2465cd18ff4c7efc25d28a791d2284812769a4bc59150c704b939f38af6d50218add3d73283;
     topsession = 411180997d839e4734ltuRfI430fe09f46b7eb30ad2a48e229428431;
     };
     ret =     (
     "SUCCESS::\U8c03\U7528\U6210\U529f"
     );
     v = "*";
     }
     */
    @autoreleasepool
    {
        NSString *api_com_taobao_client_mtop_getUserSessionKey = [URLFactory get_com_taobao_client_mtop_getUserSessionKey];
        
        ITTDINFO(@"开始请求token = %@", api_com_taobao_client_mtop_getUserSessionKey);
        NSError *error = nil;
        NSURL *requestUrl = [NSURL URLWithString: api_com_taobao_client_mtop_getUserSessionKey];
        NSDictionary *resultDic = [[NSString stringWithContentsOfURL: requestUrl
                                                            encoding: NSUTF8StringEncoding 
                                                               error: &error] JSONValue];
        ITTDINFO(@"%@",  resultDic);
        ITTDINFO(@"%@", [[resultDic objectForKey: @"ret"] objectAtIndex: 0] );
        if (error || !resultDic || [resultDic count] <= 0 || ([[[resultDic objectForKey: @"ret"] objectAtIndex: 0] rangeOfString: @"SUCCESS"].location == NSNotFound))
        {
            if (![self isCancelled])
            {
                if (_delegate && [_delegate respondsToSelector: _failSel])
                {
                    NSString *reason = [[resultDic objectForKey: @"ret"] objectAtIndex: 0];
                    [_delegate performSelectorOnMainThread: _failSel withObject: reason waitUntilDone: NO];
                }
            }
            
#ifdef DEBUG
            NSString *info = [NSString stringWithFormat: @"位置：%s ,%d行, crash原因：%@", __FUNCTION__, __LINE__, @"获取token失败"];
            NSAssert(0, info);
#endif
        }else
        {
            CoreDataManager *coreDataManager = [CoreDataManager sharedCoreDataManager];
            LFAccount *account = [coreDataManager getCurrentLoggedInAccount];
            
            NSDictionary *dataDic = [resultDic objectForKey: @"data"];
            NSString *ecode = [dataDic objectForKey: @"ecode"];
            NSString *nick = [dataDic objectForKey: @"nick"];
            NSString *sid = [dataDic objectForKey: @"sid"];
            NSString *timeStr = [dataDic objectForKey: @"time"];
            NSString *token = [dataDic objectForKey: @"token"];
            NSString *topsession = [dataDic objectForKey: @"topsession"];
            ITTDINFO(@"%@\n", dataDic);
            
            //获取登陆时间
            NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
            [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
            [dateFormatter setDateFormat:@"yyyyMMdd"];
            NSDate *time = [dateFormatter dateFromString: timeStr];
            
            ITTDINFO(@"\necode = %@\n nick = %@\n sid = %@\n date = %@\n token = %@\n topsession = %@\n", \
                     ecode,     nick,       sid,        time,        token,            topsession);
            
            account.ecode = ecode;
            account.nick = nick;
            account.sid = sid;  //别名wapsession 用于：在方位wab网页的时候加入此参数，以鉴别用户已经登陆，也有助于开发者获取“流量佣金”
            account.time = time;
            account.token = token;
            account.topsession = topsession;
            
         BOOL saveSign = [coreDataManager saveChangesToCoreData];
            if (!saveSign)
            {
#ifdef DEBUG
                NSString *rsason = [NSString stringWithFormat: @"%s, %d", __FUNCTION__, __LINE__];
                NSAssert(0, rsason);
#endif
            }
            
            if (![self isCancelled])
            {
                if (_delegate && [_delegate respondsToSelector: _successSel])
                {
                    [_delegate performSelectorOnMainThread: _successSel 
                                                withObject: nil 
                                             waitUntilDone: NO];
                }
            }
        }
    }
}

@end
